// APP
// Main.html第一次点击对应Tab时候初始化页面
//if (window.plus) {
//    //ready();
//} else {
//    document.addEventListener('plusready', ready, false);
//}

// Web
$(function () {
    if (AGENT_CLIENT.WEB) {
        ready();
    } else if (AGENT_CLIENT.APP) {
        $(".main").css("padding-bottom", "2px");
    }
});

// 初始化方法
function ready() {
    var thisPage = null,
        user = null,
        html = [],
        isChecked = false,
        goodsData = {},
        shopFav = null;

    var shoppingcartPage = function () {
        this.init();
    };

    shoppingcartPage.prototype = {
        init: function () {
            this.initData();
            this.bindEvent();
        },
        initData: function () {
            user = getLocalStorage(STORAGE_MANAGER.user);
            if (!user || !user.id) {
                redirect("../account/login.html");
                return false;
            }
            $.ajax({
                type: "POST",
                url: CONFIG_MANAGER.RequstUrl + "v1/cart/" + user.id,
                async: true,
                headers: {token: user.token},
                beforeSend: function () { $.showWaiting("加载中..."); }
            }).done(function (data) {
                thisPage.loadCartdata(data);
            }).fail(function (data) {
                var infor = JSON.parse(data);
                $.toast(infor.message);
            }).always(function () {
                $.closeWaiting();
            });
        },
        loadCartdata: function (data) {
            var query = {
                "member_id": user.id,
                "goods": [],
            };
            var i = 0;
            while (data[i]) {
                var goods_i = {
                    "shop_id": data[i].shop_id,
                    "shop_activity_no": data[i].activity_no,
                    "goods_detail": [{
                        "goods_id": data[i].sku_id,
                        "qty": data[i].qty,
                        "suite_no": data[i].suit_no,
                        "activity_no": data[i].activity_no,
                    }]
                };
                query.goods.push(goods_i);
                i++;
            }
            query = {
                "member_id": 21,
                "region_no": "",
                "address": "",
                "platform_no": "",
                "confirm_order_flag": 1,
                "goods": [
                    {
                        "shop_id": 159,
                        "shop_activity_no": "",
                        "goods_detail": [
                            {
                                "goods_id": 4587,
                                "qty": 2,
                                "suite_no": "",
                                "activity_no": "3101201509021471",
                                "goods_flag": 1
                            }
                        ]
                    }
                ]
            };
            $.ajax({
                type: "POST",
                url: CONFIG_MANAGER.RequstUrl + "v1/cart/getgoods",
                async: true,
                headers: {token: user.token},
                data: query,
            }).done(function (data) {
                thisPage.paintCarthtml(data)
            }).always(function () {
                $.closeWaiting();
            });
        },
        paintCarthtml: function (data) {
            goodsData = data;
            var i = 0, shop = data.goods, subTotal = 0, subCoinTotal = 0, strStyle = "", cacheProductCount = 0;
            if (data.platformno) {
                html.push('<p class="qcmyh mbbottom">全场满¥699减100，并且免收邮费</p>');
            }
            //店铺
            while (shop[i]) {
                html.push('<div ' + strStyle + ' class="shop-group-item mbtopbottom">');
                html.push('<div class="shop-title mbbottom">');
                html.push('<div class="item">');
                html.push('<div class="shop-title-content">');
                html.push('<span class="shop-title-name">');
                html.push('<b class="checkboxFour">');
                html.push('<input type="checkbox" value="1" id="checkbox-1-1_shop_' + i + '" name="RadioGroup1" class="checkbox-gx">');
                html.push('<label for="checkbox-1-1_shop_' + i + '"></label>');
                html.push('</b>' + shop[i].shop_name);
                html.push('</span>');
                html.push('<div class="shop-title-detail">');
                html.push('<span id="coupon_shop_' + i + '" class="mbright" style="display:inline-block;text-align:center;">优惠券</span>');
                html.push('<span id="give_goods_' + i + '" style="display:inline-block;width:50px;text-align:center;">换购</span>');
                html.push('</div>');
                html.push('</div>');
                html.push('</div>');
                html.push('</div>');

                //商品
                var goods = shop[i].goods_detail;
                var j = 0;
                var lastGoodsindex = (goods[j].length - 1);
                while (goods[j]) {
                    html.push('<ul class="shp-cart-list">');
                    html.push('<li id="goods_' + i + '_' + j + '" class="shp-gwc mbbottom">');
                    html.push('<div class="items">');
                    html.push('<div class="check-wrapper">');
                    html.push('<b class="checkboxFour">');
                    html.push('<input type="checkbox" value="1" id="checkbox-1-1_goods_' + i + '_' + j + '" name="RadioGroup2" class="checkbox-gx">');
                    html.push('<label for="checkbox-1-1_goods_' + i + '_' + j + '"></label>');
                    html.push('</b>');
                    html.push('</div>');

                    //商品名称
                    html.push('<div class="shp-cart-item-core shp-gwcny">');
                    html.push('<a class="cart-product-cell-1" href="javascript:void(0);">');
                    html.push('<img class="cart-photo-thumb" src="' + getImageUrl(goods[j].logo, 59, 59) + '">');
                    html.push('</a>');
                    html.push('<div class="cart-product-cell-2">');
                    html.push('<div name="productName" class="cart-product-name1 cart-product-name2">');
                    html.push('<span class="w40">' + goods[j].name + '</span>');
                    html.push('</div>');

                    //添加减少个数
                    html.push('<div name="addReduce" class="shp-cart-opt hide" >');
                    html.push('<div class="quantity-wrapper">');
                    html.push('<a tip="' + goods[j].sku_id + '" id="reduce_' + i + '_' + j + '" class="quantity-decrease color-hei" href="javascript:void(0);">-</a>');
                    html.push('<input type="text" id="quantity_' + i + '_' + j + '" value="' + goods[j].qty + '" class="quantity" size="4" placeholder="0">');
                    html.push('<a tip="' + goods[j].sku_id + '" id="add_' + i + '_' + j + '" class="quantity-increase" href="javascript:void(0);">+</a>');
                    html.push('</div>');
                    html.push('</div>');

                    //商品规格
                    html.push('<div class="cart-product-name w40"><a href="javascript:void(0);">');
                    var spec = goods[j].spec, k = 0;
                    if (spec[k]) {
                        html.push('<span>' + spec[k].name + '：' + spec[k].value + '</span>');
                    }
                    html.push('</a></div>');

                    //商品价格和抵用星币
                    html.push('<span class="jinbi"><b><img src="../../images/jbtub.jpg"></b><span id="coin_' + i + '_' + j + '"></span>' + goods[j].coin + '</span>+');
                    html.push('<span id="price_' + i + '_' + j + '" class="money">￥' + goods[j].shop_price + '</span>');
                    html.push('<span id="qty_' + i + '_' + j + '" style="float: right;font-size: 1.4rem;color: #333333;">x' + goods[j].qty + '</span>');
                    html.push('</div>');
                    html.push('<div tip="' + goods[j].sku_id + '" class="delete" style="display:none" name="deleteCurentCart">删除</div>');
                    html.push('</div>');

////满减满送
//html.push('<div class="shp-gwcny">');
//html.push('<p class="shp-ms shp-ms1">满送</p>');
//html.push('<p class="shp-coudan"><i class="iconfont icon-diancha"></i>全球购买满500减100，立即凑单 </p>');
//html.push('</div>');

////优惠选择，换购商品
//if(goods[j].give_goods){
//var giveGoods = goods[j].give_goods;
//$.each(giveGoods, function(m,item) {              
//  html.push('<div tip="'+ item.skuid +'" id="givgoods_'+i+'_'+j+'" class="shp-cart-item-core sub-shp-gwcny">');
//  if( item.give_goods ){}
//  html.push('<p class="shp-ms">换购</p>');
//  html.push('<div class="cart-product-cell-3">');
//  html.push('<i class="iconfont icon-diancha"></i>');
//  html.push('</div>');
//  html.push('<a class="sub-cart-product-cell-1" href="javascript:void(0);">');
//  html.push('<img class="sub-cart-photo-thumb" src="'+ getImageUrl(item.logo,59,59) + item.logo  +'">');
//  html.push('</a>');
//  html.push('<div class="cart-product-cell-2 ">');
//  html.push('<div class=" cart-product-name1"><span>'+ item.name +'</span></div>');
//  html.push('<div class="shp-cart-opt">');
//  html.push('<p class="sub-wastebin">x'+ item.qty +'</p>');
//  html.push('</div>');
//  html.push('</div>');
//  html.push('</div>');
//});
//}

                    html.push('</div>');
                    html.push('</li>');
                    html.push('</ul>');
                    subTotal = goods[j].qty * goods[j].shop_price;
                    subCoinTotal = goods[j].qty * goods[j].coin;
                    cacheProductCount += goods[j].qty;
                    j++;
                }
                html.push('<p class="shp-heji">');
                html.push('<span>小计：</span><span class="jinbi"><b><img src="../../images/jbtub.jpg"></b>');
                html.push('<span id="subCoinTotal_' + i + '">' + subCoinTotal + '</span></span>+');
                html.push('<span id="subTotal_' + i + '"  class="money">￥' + subTotal + '</span>');
                html.push('</p>');
                html.push('</div>');
                i++;
            }
            setLocalStorage(STORAGE_MANAGER.cacheproductcount, cacheProductCount);
            $("#main").html(html.join(''));
            var footerHeight = $("#footbg").height();
            $("#goCalculate").css({"bottow": footerHeight + "px"});
        },
        bindEvent: function () {
            //点击回退
            $("#back").on("tap", function () {
                back();
            });

            //绑定添加减少商品数量事件
            this.addOrSubNumber();

            //编辑购物车中的商品
            this.editCart();

            //选中商品
            this.checkCartProduct();

            //删除商品
            this.deletProduct();

            //优惠券选择
            this.couponShop();

            //点击去结算
            $("#goBanlance").on("tap", function () {
                if (parseInt($("#goodsCount").html()) < 1) {
                    $.alert("请选择一件商品");
                    return false;
                } else {
                    redirect("confirmOrder.html");
                    return false;
                }
            });
        },
        editCart: function () {
            //编辑所有
            $("#editCart").on("tap", function () {
                var titleSpan = $(this).find("span:first");
                var isEdit = ("编辑" == titleSpan.html()) ? true : false;
                if (isEdit) {
                  $("div.delete").show().animate({"width": "18%"}, 400);
                  $("div[name='productName']").hide(400);
                  $("div[name='addReduce']").show(400);
                  titleSpan.html("完成");
                } else {
                  $("div.delete").animate({"width": "0%"}, 400);
                  $("div[name='productName']").show(400);
                  $("div[name='addReduce']").hide(400);
                  titleSpan.html("编辑");
                }
            });
        },
        //删除商品
        deletProduct: function () {
            $("#main").on("tap", "div[name='deleteCurentCart']", function () {
                var title = $(this).html(), that = $(this), sku = $(this).attr("tip");
                if ("删除" == title) {
                    $.ajax({
                        type: "DELETE",
                        url: CONFIG_MANAGER.RequstUrl + "v1/cart/" + user.id + "/" + sku + "/1",
                        async: true
                    }).done(function (data) {
                        $.alert("删除成功", function () { that.html("已删除").css("background-color", "#ababab"); });
                    }).fail(function (data) {
                        var infor = JSON.parse(data);
                        $.toast(infor.Message);
                    });
                }
            });
        },
        //添加减少数量
        addOrSubNumber: function () {
            var strId = '', suffix = '', quantity = 0, type = '', coin = 0, price = 0, sku = "";
            //增加，减少商品数量
            $("#main").on("tap", "a[id^='reduce_'],a[id^=add_]", function () {
                strId = $(this).prop("id");
                suffix = strId.match(/_\w*/);
                _suffix = strId.match(/_\w/);
                type = $(this).html();
                if (suffix) {
                    quantity = $("#quantity" + suffix).val();
                    coin = $("#coin" + suffix).html();
                    price = $("#price" + suffix).html().match(/\d+/)[0];
                    sku = $(this).attr("tip");
                    if ("+" == type) {
                        quantity++;
                        thisPage.modifyProductNum("+", sku);
                    } else {
                        if (quantity < 2) {
                            return;
                        }
                        quantity--;
                        thisPage.modifyProductNum("-", sku);
                    }
                    $("#quantity" + suffix).val(quantity);
                    $("#qty" + suffix).html("x" + quantity);
                    $("#subCoinTotal" + _suffix).html(quantity * coin);
                    $("#subTotal" + _suffix).html("￥" + (quantity * price));
                }
                //计算总价
                thisPage.calculatePrice();
            });
        },
        //调用接口修改商品个数
        modifyProductNum: function (type, skuid) {
            var requestUrl = CONFIG_MANAGER.RequstUrl;
            if ('+' == type) {
                requestUrl += "v1/cart/plus/" + user.id + "/" + skuid;
            } else {
                requestUrl += "v1/cart/minus/" + user.id + "/" + skuid;
            }
            $.ajax({
                type: "PUT",
                url: requestUrl,
                async: true,
                headers: {token: user.token}
            }).done(function (data) {

            }).fail(function (data) {
                var infor = JSON.parse(data);
                $.toast(infor.Message);
            });
        },
        //所有checkbox事件
        checkCartProduct: function () {
            $("#checkbox-1-1_selectAll").prop("checked", false);
            //商店名称旁边的checkbox选中
            $("#main").on("click", "input[id^='checkbox-1-1_shop']", function () {
                var shopId = $(this).attr("id"),
                    length = shopId.length,
                    shopIndex = shopId.substr((length - 1), 1);
                if ($(this).is(":checked")) {
                    isChecked = true;
                } else {
                    isChecked = false;
                }
                $("input[id^='checkbox-1-1_goods_" + shopIndex + "']").prop("checked", isChecked);
                if ($("input[id^='checkbox-1-1_shop']:checked").length == $("input[id^='checkbox-1-1_shop']").length) {
                    isChecked = true;
                } else {
                    isChecked = false;
                }
                $("#checkbox-1-1_selectAll").prop("checked", isChecked);
                //计算总价
                thisPage.calculatePrice();
            });

            //商品傍边的checkbox选中
            $("#main").on("click", "input[id^='checkbox-1-1_goods']", function () {
                var goodsId = $(this).attr("id").substr(-3, 1);
                if ($("input[id^='checkbox-1-1_goods_" + goodsId + "']:checked").length == $("input[id^='checkbox-1-1_goods_" + goodsId + "']").length) {
                    isChecked = true;
                } else {
                    isChecked = false;
                }
                $("input[id^='checkbox-1-1_shop_" + goodsId + "']").prop("checked", isChecked);

                if ($("input[id^='checkbox-1-1_goods']:checked").length == $("input[id^='checkbox-1-1_goods']").length) {
                    isChecked = true;
                } else {
                    isChecked = false;
                }
                $("#checkbox-1-1_selectAll").prop("checked", isChecked);

                //计算总价
                thisPage.calculatePrice();
            });

            //选择所有checkbox选中
            $("#checkbox-1-1_selectAll").on("click", function () {
                if ($(this).is(":checked")) {
                    isChecked = true;
                } else {
                    isChecked = false;
                }
                $("input[id^='checkbox-1-1_goods']").prop("checked", isChecked);
                $("input[id^='checkbox-1-1_shop']").prop("checked", isChecked);

                //计算总价
                thisPage.calculatePrice();
            });
        },
        //计算总价
        calculatePrice: function () {
            var strId = "", qty = 0, coin = 0, price = 0, totalCoin = 0, total = 0, goodsCount = 0, isChecked = false;
            $.each($("input[id^='quantity']"), function () {
                suffix = $(this).prop("id").match(/_\w*/)[0];
                isChecked = $("#checkbox-1-1_goods" + suffix).is(":checked");
                if (isChecked) {
                    qty = parseInt($("#quantity" + suffix).val());
                    price = $("#price" + suffix).html().match(/\d+/)[0];
                    coin = $("#coin" + suffix).html();
                    totalCoin += qty * coin;
                    total += qty * price;
                    goodsCount += qty;
                }
            });
            $("#total").html("￥" + total);
            $("#totalCoin").html(totalCoin);
            $("#goodsCount").html(goodsCount);
        },
        //优惠活动
        couponShop: function () {
            //选择店铺换购
            $("#main").on("click", "span[id^=give_goods_]", function () {
                var goodsID = $(this).attr("id").match(/\d+/);
                var give = goodsData.goods[0].goods_detail[0].give_goods[0];
                html = [];
                html.push('<div name="item_give" class="shp-cart-item-core shp-gwcny-give">');
                html.push('<p class="shp-ms">换购</p>');
                html.push('<a class="cart-product-cell-1">');
                html.push('<img class="cart-photo-thumb" src="' + getImageUrl(give.logo, 59, 59) + '">');
                html.push('</a>');
                html.push('<div class="cart-product-cell-2" style="width: 65%;">');
                html.push('<div class="cart-product-name1 cart-product-name2"><a>');
                html.push('<span>' + give.name + '</span>');
                html.push('</a></div>');
                html.push('<div style="text-align: left;margin-top: 5px;">');
                $.each(give.spec, function (i, s) {
                    html.push('<span>' + s.name + '：' + s.value + '</span>');
                });
                html.push('<span style="float: right;">￥' + give.shopprice + '</span>');
                html.push('</div>');
                html.push('</div>');
                html.push('</div>');
                $("#active_item").html(html.join(''));
                $("#active_title").html("换购商品");
                $("#givegoodsback").show();
                $("#givegoodspop").show();
                setTimeout(function () {
                    $("#givegoodspop").addClass("moveFromBottom-moved");
                }, 200);
            });
            //选中店铺某个换购商品
            $("#givegoodspop").on("tap", "#active_item>div[name='item_give']", function () {
                var item = goodsData.goods[0].goods_detail[0].give_goods[0];
                html = []
                html.push('<div class="shp-cart-item-core sub-shp-gwcny">');
                html.push('<p class="shp-ms">换购</p>');
                html.push('<div name="remove_give" class="cart-product-cell-3">');
                html.push('<i class="iconfont icon-diancha"></i>');
                html.push('</div>');
                html.push('<a class="sub-cart-product-cell-1" href="javascript:void(0);">');
                html.push('<img class="sub-cart-photo-thumb" src="' + getImageUrl(item.logo, 59, 59) + '">');
                html.push('</a>');
                html.push('<div class="cart-product-cell-2 ">');
                html.push('<div class=" cart-product-name1"><span>' + item.name + '</span></div>');
                html.push('<div class="shp-cart-opt">');
                html.push('<p class="sub-wastebin">x' + item.qty + '</p>');
                html.push('</div>');
                html.push('</div>');
                html.push('</div>');
                $("li#goods_0_0>div.items").append(html.join(''));
                $("#givegoodspop").removeClass("moveFromBottom-moved");
                setTimeout(function () {
                    $("#givegoodspop").hide();
                    $("#givegoodsback").hide();
                }, 200);
            });

            //选择店铺优惠券
            $("#main").on("tap", "span[id^=coupon_shop_]", function () {
                var goodsID = $(this).attr("id").match(/\d+/);
                var coupon = goodsData.goods[0].coupon_shop;
                if (coupon) {
                    html = [];
                    $.each(coupon, function (i, c) {
                        html.push('<div name="item_coupon" class="shp-gwcny">');
                        html.push('<p class="shp-ms shp-ms1">优惠券</p>');
                        html.push('<p class="shp-coudan">');
                        html.push(c.title);
                        html.push('</p>');
                        html.push('<p name="get_coupon" tip=' + c.coupon_no + ' class="ob-cha-select"><a class="quantity-increase">领取</a></p>')
                        html.push('</div>');
                    });
                }
                $("#active_item").html(html.join(''));
                $("#active_title").html("优惠券");

                $("#givegoodsback").show();
                $("#givegoodspop").show();
                setTimeout(function () {
                    $("#givegoodspop").addClass("moveFromBottom-moved");
                }, 200);
            });
            //领取某个优惠券
            $("#givegoodspop").on("tap", "#active_item p[name=get_coupon]", function () {
                var couponNo = $(this).attr("tip");
                var requestUrl = CONFIG_MANAGER.RequstUrl + "v1/member/coupon/gain/" + couponNo + "-" + user.id;
                $.ajax({
                    type: "GET",
                    url: requestUrl,
                    async: true,
                    headers: {token: user.token}
                }).done(function (data) {

                }).fail(function (data) {
                    var infor = JSON.parse(data);
                    $.toast(infor.Message);
                });

            });


            //取消选择
            $("body").on("click", "#cancelgivegoods,#givegoodsback", function () {
                $("#givegoodspop").removeClass("moveFromBottom-moved");
                setTimeout(function () {
                    $("#givegoodspop").hide();
                    $("#givegoodsback").hide();
                }, 200);
            });
            //删除选择
            $(".main").on("tap", "div.items div[name=remove_give]", function () {
                $(this).parent().remove();
            });


        }
    };

    thisPage = new shoppingcartPage();

}
